package com.ffyc.cemp.services.service.impl;

import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ffyc.cemp.common.exception.user.AccountNotFoundException;
import com.ffyc.cemp.common.exception.user.BadCredentialsException;
import com.ffyc.cemp.common.exception.user.UsernameHasExistedException;
import com.ffyc.cemp.dao.mapper.IUserMapper;
import com.ffyc.cemp.domain.entity.User;
import com.ffyc.cemp.services.service.IUserService;
import com.ffyc.cemp.tools.BloomFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserMapper userMapper;

    @Override
    public User login(String username, String password) {
        //判断用户名是否存在
        User checkedUser = userMapper.selectOne(
                new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        if (checkedUser == null) throw new AccountNotFoundException("账号不存在异常，登录失败");
        if (checkedUser.getPassword().equals(password))
            throw new BadCredentialsException("用户名|密码错误异常，登录失败");


        return checkedUser;
    }


    //username = 'gxl', password='123'
    @Override
    public void registry(User user) {
        //判断用户名是否存在
//        User checkedUser = userMapper.selectOne(
//                new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        boolean checkUsername = BloomFilterUtil.getInstance().contains(user.getUsername());
        if (checkUsername) throw new UsernameHasExistedException("用户名已注册异常，注册失败");

        //密码加密
        String newPass = SmUtil.sm3(user.getPassword());
        user.setPassword(newPass);

        //生成一个分布式环境下唯一字符串UUID
        String sign = UUID.randomUUID().toString();
        user.setSign(sign);

        user.setRegistTime(new Date());
        user.setUpdateTime(new Date());
        user.setUpdateby(user.getUsername());

        userMapper.insert(user);
        BloomFilterUtil.getInstance().add(user.getUsername()); //更新布隆过滤器

    }

    @Override
    public List<String> preHotUsername() {
        List<User> users = userMapper.selectList(null);
        List<String> usernames = new ArrayList<>();
        users.forEach(u -> {
            usernames.add(u.getUsername());
        });
        return usernames;
    }
}
